﻿using System;
using System.Collections.Generic;
using System.Linq;
using TuxedoLib;

namespace SpaceSquirrel
{
	public class TileTemplate
	{
		public string id;
		public bool solid;
		public bool coveredA;
		public bool coveredB;
		public bool coveredC;
		public bool coveredD;
		public bool isDoor;
		public bool isLadder;
		public bool isTop;
		public bool isWater;
		public bool isSpike;
		public bool isLava;
		public bool isIce;
		public bool isBalloon;
		public int[] primaryBalloonOffset;
		public Image[] images;
		public Image staticImage;
		public int imageCount;

		public TileTemplate(string id, string flags, string[] imagePaths)
		{
			this.id = id;
			this.solid = false;
			this.coveredA = false;
			this.coveredB = false;
			this.coveredC = false;
			this.coveredD = false;
			this.isDoor = false;
			this.isLadder = false;
			this.isTop = false;
			this.isWater = id == "water" || id == "watertop";
			this.isSpike = false;
			this.isLava = false;
			this.isIce = false;
			this.isBalloon = false;
			this.primaryBalloonOffset = null;

			foreach (char flag in flags)
			{
				switch (flag)
				{
					case 'x': this.solid = true; break;
					case 'A': this.coveredA = true; break;
					case 'B': this.coveredB = true; break;
					case 'C': this.coveredC = true; break;
					case 'D': this.coveredD = true; break;
					case 'r':
					case 'R': this.isDoor = true; break;
					case 'L': this.isLadder = true; break;
					case 'J': this.isTop = true; break;
					case 'S': this.isSpike = true; break;
					case 'V': this.isLava = true; break;
					case 'I': this.isIce = true; break;
					case 'o':
						this.isBalloon = true;
						int bid = int.Parse(id.Substring(id.Length - 1));
						int[] pOffset = new int[] { 0, 0 };
						if (bid == 1) pOffset = new int[] { 1, 0 };
						if (bid == 3) pOffset = new int[] { -1, 0 };
						if (bid == 4) pOffset = new int[] { 1, -1 };
						if (bid == 5) pOffset = new int[] { 0, -1 };
						if (bid == 6) pOffset = new int[] { -1, -1 };
						this.primaryBalloonOffset = pOffset;
						break;
					case 'O':
						// was this a mistake in the map file?
						break;
					default:
						throw new InvalidOperationException("bad flag: " + flag);
				}
			}
			List<Image> images = new List<Image>();
			foreach (string path in imagePaths)
			{
				images.Add(ImageLibrary.GetImage("tiles/" + path));
			}
			this.images = images.ToArray();
			this.staticImage = null;
			if (this.images.Length == 1)
			{
				this.staticImage = this.images[0];
			}
			this.imageCount = this.images.Length;
		}

		public Image GetImage(int renderCounter)
		{
			Image image = this.staticImage;
			if (image == null)
			{
				return this.images[(renderCounter / 4) % this.imageCount];
			}
			return image;
		}
	}
}
